var http = require("../utils/http");
var qs = require('querystring');
var crypto = require('./crypto');

var appid;
var appsecret;

exports.init = function(config){
  appid = config.appid;
  appsecret = config.appsecret;
};

//微信登录校验
exports.wxAuth=function(code,callback){

  //先调用token
  getAccessToken(code,function(bool,data){

    //token获取成功 获取用户信息
    if(bool&&!data.errcode){
     // callback(data);
     var accessToken = data.access_token;
     var openId = data.openid;
     getUserInfo(accessToken,openId,callback);

    }else{
      console.log("调用微信失败 code = " +data.errcode  +"  errmsg = " + data.errmsg);
      callback(false,data.errmsg);
    }
   });
};


exports.getCode=function(url){

  //https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx01474dde2db8ff3b&redirect_uri=http%3a%2f%2ftestop.quxiangkeji.com%2fcsmj%2fcode&response_type=
//code&scope=snsapi_userinfo&state=STATE#wechat_redirect 
  var wx_url = 'https://open.weixin.qq.com/connect/oauth2/authorize'
              +'?appid=' + appid
              +'&redirect_uri=' +encodeURIComponent(url)
              +'&response_type=code' 
              +'&scope=snsapi_userinfo&state=qx' + new Date().getTime()
              +'#wechat_redirect';
  return wx_url;
};

//获取accesstoken
var getAccessToken = function(code,callback){
 
  var url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
    //等着请求参数
  var params = {
        appid: appid,
        secret:appsecret,
        code:code,
        grant_type: 'authorization_code'
      };
  if(!callback){
   console.log("获取微信accessToke :callback is null..");
   return;
  }
  //发送请求
  http.get2(url,params,callback,true);
};

//获取用户信息
var getUserInfo=function(accessToken,openid,callback){

 
  var url = 'https://api.weixin.qq.com/sns/userinfo';
    //等着请求参数
    var params = {
      access_token:accessToken,
      openid:openid,
      lang:'zh-CN'
    };

  
  //发送请求
  http.get2(url,params,callback,true);
    
};